/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.services.system;

import cn.easyplatform.ServiceException;
import cn.easyplatform.dao.EntityDao;
import cn.easyplatform.entities.EntityInfo;
import cn.easyplatform.entities.beans.project.ProjectBean;
import cn.easyplatform.entities.transform.TransformerFactory;
import cn.easyplatform.i18n.I18N;
import cn.easyplatform.services.AbstractService;
import cn.easyplatform.services.SystemServiceId;
import cn.easyplatform.services.project.ProjectService;
import cn.easyplatform.type.StateType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
@Deprecated
public class PlatformService extends AbstractService {

    private static final Logger log = LoggerFactory.getLogger(PlatformService.class);

    private Date startTime;

    @Override
    public String getId() {
        return SystemServiceId.SYS_PLATFORM;
    }

    @Override
    public String getName() {
        return I18N.getLabel("platform.name");
    }

    @Override
    public String getDescription() {
        return I18N.getLabel("platform.desp");
    }

    @Override
    public void start() throws ServiceException {
        if (getState() != StateType.STOP)
            return;
        try {
            if (log.isDebugEnabled())
                log.debug(I18N.getLabel("easyplatform.sys.common.starting",
                        getName()));
            //启动项目
            EntityDao dao = engineConfiguration.getEntityDao();
            List<EntityInfo> models = dao.getModels();
            for (final EntityInfo entity : models) {
                ProjectBean project = TransformerFactory.newInstance()
                        .transformFromXml(entity);
                AbstractService s = new ProjectService(project);
                s.setEngineConfiguration(engineConfiguration);
                try {
                    s.start();
                } catch (Exception e) {
                    if (models.size() == 1)//仅单项目
                        throw e;
                    if (log.isWarnEnabled())
                        log.warn(String.format("Failed to start project {} {}", project.getId(), project.getName()), e);
                }
            }
            // 启动背景服务
            /**int interval = engineConfiguration
             .getPlatformAttributeAsInt("cacheValidationInterval");
             if (interval == 0)
             interval = 60;// 1分钟
             String jobId = RandomStringUtils.randomAlphabetic(16);
             JobDataMap dm = new JobDataMap();
             JobDetail jobDetail = JobBuilder.newJob().ofType(CacheValidationJob.class).withIdentity(jobId, getId()).withDescription(I18N
             .getLabel("easyplatform.sys.scheduler.entity.cache")).setJobData(dm).build();
             SimpleTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobId, getId()).startAt(new Date(System.currentTimeMillis() + 60000)).withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(interval)).build();

             IScheduleService sched = engineConfiguration.getScheduleService();
             sched.start(jobDetail, trigger);
             jobWorkers[0] = jobId;*/

            //会话检查服务
/**            int interval = engineConfiguration
                    .getPlatformAttributeAsInt("sessionValidationInterval");
            if (interval == 0)
                interval = (int) (DefaultSessionManager.DEFAULT_SESSION_VALIDATION_INTERVAL / 1000);
            String jobId = "SessionValidation";
            JobDataMap dm = new JobDataMap();
            JobDetail jobDetail = JobBuilder.newJob().ofType(SessionValidationJob.class).withIdentity(jobId, "easyplatform").withDescription(I18N
                    .getLabel("easyplatform.sys.scheduler.session")).setJobData(dm).build();
            SimpleTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobId, "easyplatform").startAt(new Date(System.currentTimeMillis() + 60000)).withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(interval)).build();
            IScheduleService sched = engineConfiguration.getScheduleService();
            sched.start(jobDetail, trigger);
            jobWorkers[0] = jobId;*/

            setState(StateType.START);
            startTime = new Date();
            if (log.isDebugEnabled())
                log.debug(I18N
                        .getLabel("easyplatform.sys.common.started", getName()));
        } catch (Exception ex) {
            if (log.isWarnEnabled())
                log.warn(I18N.getLabel("easyplatform.sys.common.fail", getName()),
                        ex);
            throw new ServiceException(I18N.getLabel("easyplatform.sys.common.fail",
                    getName(), ex.getMessage()));
        }
    }

    @Override
    public void stop() throws ServiceException {
        if (getState() == StateType.STOP)
            return;
        if (log.isDebugEnabled())
            log.debug(I18N.getLabel("easyplatform.sys.common.stopping", getName()));
        setState(StateType.STOP);
        startTime = null;
        if (log.isDebugEnabled())
            log.debug(I18N.getLabel("easyplatform.sys.common.stopped", getName()));
    }

    @Override
    public Map<String, Object> getRuntimeInfo() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(I18N.getLabel("easyplatform.sys.common.start.time"), startTime);
        return map;
    }

    @Override
    public Date getStartTime() {
        return startTime;
    }
}
